import express from 'express';
import multer from 'multer';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import fs from 'fs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const router = express.Router();

// 确保上传目录存在
const uploadDir = join(__dirname, '..', 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 处理中文文件名编码的函数
function fixChineseFilename(filename) {
  if (!filename) return '未知文件';
  
  let fixedName = filename;
  
  // 如果文件名是 Buffer，先转换为字符串
  if (Buffer.isBuffer(filename)) {
    try {
      fixedName = filename.toString('utf8');
    } catch (error) {
      console.warn('Buffer 转字符串失败:', error);
      fixedName = filename.toString() || '未知文件';
    }
  }
  
  // 检查是否包含乱码字符
  if (typeof fixedName === 'string') {
    // 如果文件名包含中文字符但看起来像乱码，尝试修复
    if (/[^\x00-\x7F]/.test(fixedName) && /[^\u4e00-\u9fa5a-zA-Z0-9\s\-_\.]/.test(fixedName)) {
      try {
        // 尝试多种编码方式
        const encodings = ['utf8', 'latin1', 'gbk', 'gb2312'];
        for (const encoding of encodings) {
          try {
            if (encoding === 'latin1') {
              const buffer = Buffer.from(filename, 'latin1');
              const decoded = buffer.toString('utf8');
              if (decoded && !/[^\x00-\x7F]/.test(decoded) || /[\u4e00-\u9fa5]/.test(decoded)) {
                fixedName = decoded;
                console.log(`使用 ${encoding} 编码成功解码文件名:`, decoded);
                break;
              }
            } else {
              const decoded = filename.toString(encoding);
              if (decoded && !/[^\x00-\x7F]/.test(decoded) || /[\u4e00-\u9fa5]/.test(decoded)) {
                fixedName = decoded;
                console.log(`使用 ${encoding} 编码成功解码文件名:`, decoded);
                break;
              }
            }
          } catch (e) {
            continue;
          }
        }
      } catch (error) {
        console.warn('编码修复失败:', error);
      }
    }
  }
  
  return fixedName;
}

// 配置 multer 存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名，保留原始扩展名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    // 使用原始文件名作为前缀，避免全是 "file-" 开头
    const nameWithoutExt = path.basename(file.originalname, ext);
    cb(null, nameWithoutExt + '-' + uniqueSuffix + ext);
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  const allowedTypes = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/x-dxf',
    'text/plain'
  ];
  
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('不支持的文件类型！'), false);
  }
};

// 配置 multer
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 50 * 1024 * 1024, // 50MB 限制
  }
});

// 获取文件列表
router.get('/', (req, res) => {
  try {
    const files = [];
    
    if (fs.existsSync(uploadDir)) {
      const fileList = fs.readdirSync(uploadDir);
      
      fileList.forEach(filename => {
        // 排除 .gitkeep 文件和 .meta.json 元数据文件
        if (filename !== '.gitkeep' && !filename.endsWith('.meta.json')) {
          const filePath = join(uploadDir, filename);
          const stats = fs.statSync(filePath);
          
          // 优先尝试读取元数据文件获取原始文件名
          let originalName = filename;
          let uploadTime = stats.mtime.toISOString();
          let mimetype = getMimeType(filename);
          
          const metadataPath = filePath + '.meta.json';
          if (fs.existsSync(metadataPath)) {
            try {
              const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf8'));
              originalName = metadata.originalName || filename;
              uploadTime = metadata.uploadTime || uploadTime;
              mimetype = metadata.mimetype || mimetype;
              
                             // 确保中文文件名正确显示 - 移除不必要的重复解码
               // 文件名已经通过 fixChineseFilename 函数正确解码，不需要再次处理
            } catch (metaError) {
              console.warn(`无法读取文件 ${filename} 的元数据:`, metaError);
            }
          } else {
            // 如果没有元数据文件，尝试从文件名中提取原始文件名（去掉时间戳和随机数）
            const ext = path.extname(filename);
            const nameWithoutExt = path.basename(filename, ext);
            // 匹配格式：原始文件名-时间戳-随机数.扩展名
            const match = nameWithoutExt.match(/^(.+)-(\d+)-(\d+)$/);
            if (match) {
              originalName = match[1] + ext;
            }
          }
          
          files.push({
            id: filename,
            originalName: originalName,
            filename: filename,
            size: stats.size,
            url: `/uploads/${filename}`,
            uploadTime: uploadTime,
            mimetype: mimetype
          });
        }
      });
    }
    
    res.json({
      success: true,
      data: files,
      message: '获取文件列表成功'
    });
  } catch (error) {
    console.error('获取文件列表失败:', error);
    res.status(500).json({
      success: false,
      error: {
        message: '获取文件列表失败',
        details: error.message
      }
    });
  }
});

// 文件上传
router.post('/', upload.single('file'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        error: {
          message: '没有选择文件'
        }
      });
    }
    
    // 使用专门的函数处理中文文件名编码问题
    const originalName = fixChineseFilename(req.file.originalname);
    
    console.log('原始文件名:', req.file.originalname);
    console.log('处理后的文件名:', originalName);
    
    // 创建元数据文件来保存原始文件名
    const metadataPath = join(uploadDir, req.file.filename + '.meta.json');
    const metadata = {
      originalName: originalName,
      uploadTime: new Date().toISOString(),
      mimetype: req.file.mimetype
    };
    
    try {
      fs.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2), 'utf8');
    } catch (metaError) {
      console.warn('无法保存文件元数据:', metaError);
    }
    
    const fileData = {
      id: req.file.filename,
      originalName: originalName,
      filename: req.file.filename,
      size: req.file.size,
      url: `/uploads/${req.file.filename}`,
      uploadTime: new Date().toISOString(),
      mimetype: req.file.mimetype
    };
    
    res.json({
      success: true,
      message: '文件上传成功',
      data: fileData
    });
  } catch (error) {
    console.error('文件上传失败:', error);
    res.status(500).json({
      success: false,
      error: {
        message: '文件上传失败',
        details: error.message
      }
    });
  }
});

// 删除文件
router.delete('/:filename', (req, res) => {
  try {
    const filename = req.params.filename;
    const filePath = join(uploadDir, filename);
    
    if (fs.existsSync(filePath)) {
      // 删除主文件
      fs.unlinkSync(filePath);
      
      // 同时删除元数据文件
      const metadataPath = filePath + '.meta.json';
      if (fs.existsSync(metadataPath)) {
        try {
          fs.unlinkSync(metadataPath);
        } catch (metaError) {
          console.warn(`无法删除元数据文件 ${metadataPath}:`, metaError);
        }
      }
      
      res.json({
        success: true,
        message: '文件删除成功'
      });
    } else {
      res.status(404).json({
        success: false,
        error: {
          message: '文件不存在'
        }
      });
    }
  } catch (error) {
    console.error('删除文件失败:', error);
    res.status(500).json({
      success: false,
      error: {
        message: '删除文件失败',
        details: error.message
      }
    });
  }
});

// 根据文件扩展名获取 MIME 类型
function getMimeType(filename) {
  const ext = path.extname(filename).toLowerCase();
  const mimeTypes = {
    '.pdf': 'application/pdf',
    '.doc': 'application/msword',
    '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    '.xls': 'application/vnd.ms-excel',
    '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    '.ppt': 'application/vnd.ms-powerpoint',
    '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    '.dxf': 'application/x-dxf',
    '.txt': 'text/plain'
  };
  
  return mimeTypes[ext] || 'application/octet-stream';
}

export default router;
